/*
	AIBID updater
	Copyright (C) 2012-2012 Metallhead <Metallhead@megabox.ru>

	HomePage:    http://code.google.com/p/aibid/

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QtNetwork/QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
#include <QDebug>
#include <QProcess>
#include <QSettings>
#include <QDesktopServices>
#include <QTextCodec>
#include <QDir>

namespace Ui {
    class MainWindow;
}

struct fileWithVersion
{
	QString type;
	QString name;
	double version;
	int number;
	uint hash;

	bool operator ==(fileWithVersion & another)
	{
		return this->name == another.name;
	}
	bool operator !=(fileWithVersion & another)
	{
		return this->version != another.version;
	}
	bool operator >(fileWithVersion & another)
	{
		return this->version > another.version;
	}
	bool operator <(fileWithVersion & another)
	{
		return this->version < another.version;
	}
};

static QString downloadAddress = "ftp://aibid.ru/aibid/";

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
	explicit MainWindow(QString name, QWidget *parent = 0);
    ~MainWindow();

private slots:
	void on_update_clicked();
	void filesListDownloaded(QNetworkReply* reply);
	void updateProgressBar(int row);
	void fileDownloaded(QNetworkReply* reply, int row, QString fileName, QString fileType);


signals:
	void downloadedCountChanged(int);

private:

    Ui::MainWindow *ui;
	int filesDownloaded;
	int filesNeededToDownload;
	void downloadFilesList();
	void incDownloadedCount(int row);
	void fillFiles(QByteArray arr, QVector<fileWithVersion> & array);
	void downloadFile(fileWithVersion file);
	void processUpdate();
	bool checkAllFiles();
	bool exit;
	bool launchAfterUpdate;
	QString programName;
	QByteArray filesLst;

	QVector<fileWithVersion> files, currFiles, filesToDownload;

};

class downloader : public QObject
{
	Q_OBJECT
public:
	downloader(QString type, int num, QString name, double version);
	void downloadFile();
private:
	QNetworkAccessManager * manager;
	int number;
	QString fileName;
	double fileVersion;
	QString fileType;
private slots:
	void sendSignal(QNetworkReply * reply);

signals:
	void signal(QNetworkReply*, int, QString, QString);
};

#endif // MAINWINDOW_H
